<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <script>
      // 作用域
      var a = 2
      var b1 = 'atguigu1'
      function fn1() {
        var a = 4
        var b2 = 'atguigu2'
        function fn2() {
          var b3 = 'atguigu3'
          var a = 6
        }
      }
    </script>

    <script>
      /* 块作用域 */
      if (flag) {
        var a = 1
        let b = 2
      }
      console.log(a) // ?
      console.log(b) // ?

      // for + var
      for(var i=0;i<5;i++) {
        setTimeout(() => {
          console.log(i) // ?
        }, 0)
      }
      
      // for + let
      for(let i=0;i<5;i++) {  // 有5个块, 5个i
        setTimeout(() => {
          console.log(i) // ?
        }, 0)
      }
      /* 
      {
        let i=0
        setTimeout(() => {
          console.log(i) // ?
        }, 0)
      }
      {let i=1}
      {let i=2}
      {let i=3}
      {let i=4}
      */
    </script>

    <script>
      /* JS是词法作用域, 也称为静态作用域 */
      var a = 2
      function fn() {
        var b = 4
        console.log(a, b) // ? ?
      }
      function fn2() {
        var a = 3
        fn()
      }
      fn2()
    </script>
  </body>
</html>
